#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2020/11/23 18:42
# @Author  : LuLu
# @FileName: Tools.py
# @Software: PyCharm

import os
import time
import pymysql
from comment.readYaml import ReadYaml


def timestamp():
    """时间戳"""
    return time.time()


def datetime():
    """datetime格式化时间"""
    return time.strftime("%Y-%m-%d_%H_%M_%S")


def sleep(seconds=1):
    """
    睡眠时间
    """
    time.sleep(seconds)


# 判断字符串中是否包含中文
def is_contains_chinese(strs):
    """

    :param strs:
    :return: 返回 是否包含中文
    """
    for _char in strs:
        if '\u4e00' <= _char <= '\u9fa5':
            return True
    return False


# 判断字符串中是否纯数字
def is_num(Str):
    """

    :param Str:
    :return: 返回是否纯数字
    """
    try:
        int(Str)
        return True
    except ValueError:
        return False


# 获取项目根目录
def get_dirabspath():
    """
    :return: 返回当前项目绝对路径
    """
    return os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))


# 选择图片

def select_pic(*fileName):
    """
    :param fileName: 传递多个参数，以'a.jpg','b.png'形式上传
    :return: 返回一个图片绝对地址
    :备注：这里需要把图片放入到项目的pic文件中，如果不存在就抛异常，事务形式，多个参数如存在不存在则整个不返回，并抛出异常
    """
    # 获取根目录
    path = get_dirabspath()
    # 拼接pic目录
    pic_path = '\\pic\\'
    try:
        for i in fileName:
            # 如果文件不存在则抛异常
            if type(i) is list:
                for x in i:
                    with open(path + pic_path + x):
                        pass
            else:
                with open(path + pic_path + i):
                    pass
    except Exception as e:
        print(f"---->找不到对应文件:{path + pic_path + i}，检查文件路径是否存在或文件名称是否正确")
        raise e
    # 拼接多选的pic图片名称
    file_list_name = str(fileName).replace("[", "").replace("]", "").replace(",", ""). \
        replace("\'", "\"").replace("(", "").replace(")", "")
    real_path = path + pic_path + file_list_name
    # 返回多选str
    return real_path


# mysql 查询
def mysql_operate(sql, database_type='tp_food_product_test1', row_num=None, line_num=None):
    """
    :param sql: sql语句
    :param database_type: 指定数据库,默认产品库
    :param row_num:第几行
    :param line_num:第几列
    :return: 查询类型的返回元祖数据或者单个字段字符串，其他不返回数据
    """
    mysql_info = ReadYaml().get_mysql_connect_info()
    if database_type.lower() in ['food', '为食网', 'tp_food_product_test1', '产品']:
        database = 'tp_food_product_test1'
    elif database_type.lower() in ['oss', '配置', 'travel_db_test1']:
        database = 'travel_db_test1'
    elif database_type.lower() in ['order', '订单', 'tp_food_order_test1']:
        database = 'tp_food_order_test1'

    conn = pymysql.connect(
        host=mysql_info['host'],
        user=mysql_info['user'],
        password=mysql_info['password'],
        database=database,
        charset=mysql_info['charset'])
    cursor = conn.cursor()
    if sql.lower().startswith("select") and not sql.lower().startswith("select into"):
        try:
            cursor.execute(sql)
            res = cursor.fetchall()
            res_text = ()
            if row_num is None and line_num is None:
                # 返回全部结果
                res_text = res
            elif row_num is not None and line_num is None:
                # 返回第几行的结果
                res_text = res[row_num - 1]
            elif row_num is None and line_num is not None:

                # 返回查询第几列结果

                line_list = []
                for line in res:
                    line_list.append(line[line_num - 1])
                res_text = tuple(line_list)
            else:
                # 返回
                res_text = res[row_num - 1][line_num - 1]
            cursor.close()  # 先关闭游标
            conn.commit()
            conn.close()  # 再关闭数据库连接
            print(f'Exec--->>> {sql} <<<---done!')
            return res_text
        except Exception as e:
            print(f'**Exec--->>> {sql} <<<---error!')
            raise e

    else:
        try:
            cursor.execute(sql)
        except Exception as e:
            conn.rollback()
            raise e
        cursor.close()  # 先关闭游标
        conn.commit()
        conn.close()  # 再关闭数据库连接
        print(f'Exec--->>> {sql} <<<---done!')


if __name__ == '__main__':
    # print(mysql_operate('select * from food_member_collect', line_num=1, row_num=1))
    select_pic(["豆腐.jpg", "肠粉.jpg"], )
